package com.zyy.game.tianlong.network.codec;

import com.alibaba.fastjson.JSON;
import com.zyy.game.tianlong.network.SocketMsg;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * 编码器 将{@link SocketMsg}对象转换为指定长度协议的二进制
 *
 * @author relufi
 * @date 2019/7/22 0022 10:24
 */
@ChannelHandler.Sharable
public class GameWebSocketEncoder extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
        if (msg instanceof SocketMsg) {
            ctx.write(new TextWebSocketFrame(JSON.toJSONString(msg)), promise);
        } else {
            ctx.write(msg, promise);
        }
    }
}
